<template>
  <div style="width: 100%; height: 100%;">
    <div id="map" class="map" style="width: 100%; height: 100%;"></div>
  </div>
</template>

<script>
import Map from 'ol/Map';
import View from 'ol/View';
import TileLayer from 'ol/layer/Tile';
import XYZ from 'ol/source/XYZ';
import LayerVector from 'ol/layer/Vector';
import SourceVector from 'ol/source/Vector';

import GeoJSON from "ol/format/GeoJSON";
import {transform} from "ol/proj";

import {defaults, Draw, Snap, Modify, Select} from "ol/interaction";

import MapStyle from "../map-style";
import MapData from "../map-data";


/**
 * 一个项目，会大量用到 geojson 数据，而不是采用 ol 的内置对象；
 *
 * 主要原因：增强项目的通用性，即便有一天不再使用 ol，需要调整的代码也会少写；
 *
 * 因此 geojson 相关的代码比重会非常大
 */
export default {
    components: {},
    data() {
        return {
            map: null
        };
    },
    mounted() {
        this.initMap();
    },
    methods: {
        initMap() {
            let layerVector = new LayerVector({
                style: MapStyle.defaultStyle
            });

            let map = new Map({
                view: new View({
                    // 把坐标投影转换为 3857（web 墨卡托投影）
                    center: transform([102.0, 0.5], 'EPSG:4326', 'EPSG:3857'),
                    zoom: 7
                }),
                layers: [
                    // 底图
                    new TileLayer({
                        source: new XYZ({url: 'https://server.arcgisonline.com/ArcGIS/rest/services/World_Street_Map/MapServer/tile/{z}/{y}/{x}'})
                    }),
                    layerVector
                ],
                target: 'map',
            });

            // 一个点击事件
            map.on('click', function (evt) {
                // 鼠标点击的坐标
                let coordinate = evt.coordinate;
                console.log('click: ' + coordinate);

                map.forEachFeatureAtPixel(evt.pixel, function (feature, layer) {
                    Layers.succeed('功能建设中！');
                });
            });

            this.map = map;

            const select = new Select({
                wrapX: false
            });

            const modify = new Modify({
                features: select.getFeatures()
            });

            // 可选中
            map.addInteraction(select);
            // 可编辑
            map.addInteraction(modify);


            // 测试用 geojson
            let geojson = MapData.geojson;

            layerVector.setSource(new SourceVector({
                features: new GeoJSON({featureProjection: 'EPSG:3857'}).readFeatures(geojson)
            }));
        }
    }
};
</script>
